package com.javapatterns.xmlproperties;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;

import org.xml.sax.SAXException;

public class XMLProperties extends Properties {
	XMLParser p = null;

	public synchronized void load(InputStream in) throws IOException {
		try {
			p = new XMLParser(in, this);
		} catch (SAXException e) {
			throw new IOException(e.getMessage());
		}
	}

	public synchronized void load(File file) throws SAXException, IOException {

		InputStream in = new BufferedInputStream(new FileInputStream(file));
		XMLParser p = null;
		try {
			p = new XMLParser(in, this);
		} catch (SAXException e) {
			System.out.println(e);
			throw e;
		}
	}

	public synchronized void save(OutputStream out, String header) {
		try {
			store(out, header);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public synchronized void store(OutputStream out, String header)
			throws IOException {
		PrintWriter wout = new PrintWriter(out);
		wout.println("<?xml version='1.0'?>");
		if (header != null) {
			wout.println("<!--" + header + "-->");
		}

		wout.print("<properties>");
		for (Enumeration e = keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();
			String val = (String) get(key);
			wout.print("\n <key name=\"" + key + "\">");
			wout.print(encode(val));
			wout.print("</key>");
		}
		wout.print("\n</properties>");
		wout.flush();
	}

	protected StringBuffer encode(String string) {
		int len = string.length();
		StringBuffer buffer = new StringBuffer(len);
		char c;

		for (int i = 0; i < len; i++) {
			switch (c = string.charAt(i)) {
			case '&':
				buffer.append("&amp;");
				break;
			case '<':
				buffer.append("&lt;");
				break;
			case '>':
				buffer.append("&gt;");
				break;
			default:
				buffer.append(c);
			}
		}

		return buffer;
	}

	public XMLProperties() {
		super();
	}

	public XMLProperties(Properties defaults) {
		super(defaults);
	}
}
